<template>
	<div class="wrapper" ref='wrapper'>
		<div class="light" v-for="(list,index) in column.count" :style="{'width':Listwidth+'px'}">
				<List
				v-for="(item,len) in ListData[index]" 
				:img="item.img" :price='item.price' 
				:title='item.title'
				:businessName='item.businessName' 
				@click="distribute(index,len)" />
			</div>
	</div>
</template>

<script lang="ts">
	import {
		defineComponent,
		onMounted,
		ref,
		reactive,
		nextTick,
		watchEffect
	} from 'vue'
	
	import List from '@components/context/Exhibition/index.vue';
	
	import {
		LoadImg
	} from './LoadImg'
	export default defineComponent({
		components: {
			List
		},
		props: {
			List: {
				type: Array,
				default: []
			}
		},
		methods:{
			distribute(index:number,len:number):void{
				var list=this.ListData[index][len]
				this.$emit('distribute',list)
			}
		},
		setup(props) {
			var Listwidth = ref(0)
			var wrapper = ref()
			var DataList = ref([])
			var ListData: any = reactive({})
			var column: any = reactive({
				FirstStart: 0,
				count: 0,
				getMin() {
					var height = null;
					var index = 0;
					for (let i = 0; i < this.count; i++) {
						height = height ? height : column['List' + i]
						var NewHeight = column['List' + i];

						if (NewHeight < height) {
							height = NewHeight;
							index = i;
						}
					}
					return index
				}
			})
			// //渲染数据
			async function renderList(list: any[]) {
				var arr: any = [];
				var len = list.length;
				arr.push(...(list.splice(column.FirstStart, len)));
				column.FirstStart = len;
				if (arr.length == 0) return;
				var urls = arr.map((item: any) => item.img)
				var pedding: any = await LoadImg(urls)
				arr.forEach((item: any, num: number) => {
					var index = column.getMin();
					var height= pedding[num].height;
					if(height){
						column['List' + index] += height;
						ListData[index].push(item)
					}
				
				})
				pedding=null
			}
			onMounted(() => {
				// 初始化数据
				var width = Number(wrapper.value.offsetWidth);
				var count = 0;
				count = parseInt(String(width / 250));
				if (width <= 500) count = 2;
				Listwidth.value = parseInt(String(width / count));
				column.count = count
				for (var i = 0; i < count; i++) {
					ListData[i] = []
					column['List' + i] = 0
				}
				// props.List
				watchEffect(() => {
					var datalist: any = Array.from(props.List)
					renderList(datalist)
				})
			})

			return {
				column,
				Listwidth,
				wrapper,
				ListData,
			}
		}
	})
</script>

<style scoped="scoped">
	.wrapper {
		width: 100%;
		background-color: #f2f2f2;
		display: flex;
		flex-direction: row;
	}

	.List{
		width: calc(100% - 5px);
		margin: 5px auto;
	}
</style>
